# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: Mux_Heater_IV.py
  @time: 2022/5/11 9:35
  @desc:
"""

import time

from math import *

from ATS.application.LCR_App.U2722A_App import U2722A_App
from ATS.application.LASER_App.L8164B_App import L8164B_App
from ATS.application.LASER_App.N7744C_App import N7744C_App
from ATS.datamanager import data_transfer_station as DataTransferStation
from ATS.application.VNA_App.N5225B_App import N5225BApp
from scipy.signal import savgol_filter
from ATS.util.calcu_step_util import get_points_list
from ATS.util.save_data_2_csv_util import saveData2CSV
from matplotlib import pyplot as plt
from ATS.switchdriver.LightSwitchDriver import LightSwitchDriver
import numpy as np
from utils.find3db_util import find3db_util
from utils.find_first_minimum_util import find_first_minimaxmum
from utils.save_setting_2_ini import save_ini_info
from gui import constant
from collections import namedtuple
from utils.log_util import loggings


# def Mux_Heater_IV(start_voltage=0, stop_voltage=2.5, points=101, sweep_channel=3, sweep_channel_range="120mA",
#                   sweep_channel_limit=0.12,
#                   bias_channel=2, bias_channel_voltage=-2, bias_channel_current_range="100uA",
#                   bias_channel_limit=0.0001):
def Mux_Heater_IV(para):
    try:
        result_data = namedtuple("result_data", "subdie,test_item,curve_type,test_result")
        l8164b_app = L8164B_App("SS3")

        l8164b_app.set_power_unit()
        l8164b_app.set_power_value(para.l8164_setting["power_value"])
        l8164b_app.set_wave_length(para.l8164_setting["wave_length"][0])

        l8164b_app.output_on()

        smu_setting = para.smu_setting
        print("smu_setting", smu_setting)
        smu_dict = {}

        # smu voltage_list channel nplc current_range current_limit //mode sweep
        #
        mes_plans_dict = {"var_func": None, "var1": None, "measure_func": None}
        init_set_list = []
        for smu in smu_setting:
            if smu["smu"] not in smu_dict:
                smu_dict[smu["smu"]] = U2722A_App(smu["smu"])
            current_inst = smu_dict[smu["smu"]]
            current_voltage_list = smu["voltage_list"]
            current_channel = smu["channel"]
            current_channel_nplc = smu["nplc"]
            current_channel_range = smu["current_range"]
            current_channel_limit = smu["current_limit"]
            init_set_list += [lambda x=current_channel, inst_obj=current_inst: inst_obj.set_voltage_range(x),
                              lambda x=current_channel_nplc, y=current_channel,
                                     inst_obj=current_inst: inst_obj.set_current_nplc(x, y),
                              lambda x=current_channel_range, y=current_channel_limit,
                                     z=current_channel, inst_obj=current_inst: inst_obj.set_current_range_limit(x, y,
                                                                                                                z)]
            if smu["mode"] == "sweep":
                mes_plans_dict["var1"] = current_voltage_list
                mes_plans_dict["var_func"] = lambda volt, x=current_channel, inst_obj=current_inst: \
                    inst_obj.set_voltage(volt, x)
            else:
                init_set_list += [lambda volt=current_voltage_list[0], x=current_channel, inst_obj=current_inst: \
                                      inst_obj.set_voltage(volt, x)]

            if smu["is_measure"]:
                mes_plans_dict["measure_func"] = lambda x=current_inst: abs(
                    float(current_inst.get_current_value(current_channel)))

        # set init
        for inst_set_func in init_set_list:
            inst_set_func()  # 设置SMU

        # read mes
        current_list = []  # result list
        mes_func = mes_plans_dict["measure_func"]
        if mes_func:  # mes func不为空
            if mes_plans_dict["var1"]:  # sweep
                for volt in mes_plans_dict["var1"]:
                    print("volt", volt)
                    mes_plans_dict["var_func"](volt)
                    current_list.append(mes_func())
            else:
                current_list.append(mes_func())  # spot

        print("current_list", current_list)
        voltage_list = [float(i) for i in mes_plans_dict["var1"]]
        if all([voltage_list, current_list]):
            DataTransferStation.get_DTS().postarraydata("test", result_data(para.subdie, para.test_item, "line",
                                                                            (voltage_list, current_list)))
            vh = find_first_minimaxmum(voltage_list, current_list)
            save_ini_info(constant.REMEMBER_VALUE, "remember_value", "vh", str(vh))

    except Exception as e:
        loggings.error("Mux_Heater_IV" + str(e))


def plot_curve1(x_data, y_data):
    plt.plot(x_data, y_data, "b")
    plt.xlabel("Voltage")
    plt.ylabel("Current")
    plt.grid(True)
    plt.show()


Mux_Heater_IV(locals()["para"])
